/*************************************************
* Title：TinyToolKit
* Author：Opportunity 
* Describe：实现射线检测交互
* CreateTime：2021-10-20 16:18:13
* Version：1.0
* Modify Recorder：
*************************************************/

using UnityEngine;

namespace TinyToolKit
{
    [RequireComponent(typeof(MouseRaycast))]
    public class RaycastInteractionCtr : MonoBehaviour
    {
        [Header("检测"), SerializeField] private RaycastInteractionBase curTarget;

        [SerializeField] private bool _canRaycast = true;

        private void Active()
        {
            _canRaycast = true;
        }

        private void Deactive()
        {
            _canRaycast = false;
            curTarget = null;
        }

        public void OnRaycastEnter(RaycastHit hit)
        {
            if (_canRaycast == false) return;

            if (curTarget != null)
                curTarget.OnExit();
            RaycastInteractionBase raycastInteraction = hit.transform.GetComponent<RaycastInteractionBase>();
            if (raycastInteraction != null)
            {
                raycastInteraction.OnEnter();
                curTarget = raycastInteraction;
            }
        }

        public void OnRaycastHover(RaycastHit hit)
        {
            if (_canRaycast == false) return;

            RaycastInteractionBase raycastInteraction = hit.transform.GetComponent<RaycastInteractionBase>();
            if (raycastInteraction == null) return;

            if (raycastInteraction == curTarget)
            {
                curTarget.OnHover(hit);
            }
            else
            {
                if (curTarget != null)
                    curTarget.OnExit();

                raycastInteraction.OnEnter();
                curTarget = raycastInteraction;
            }
        }

        public void OnRaycastExit(RaycastHit hit)
        {
            if (_canRaycast == false) return;

            RaycastInteractionBase raycastInteraction = hit.transform.GetComponent<RaycastInteractionBase>();
            if (raycastInteraction != null && raycastInteraction == curTarget)
                curTarget.OnExit();

            curTarget = null;
        }
    }
}